import 'dart:async';

import 'package:client_flutter_door/bean/cabinet.dart';
import 'package:client_flutter_door/http/box.dart';
import 'package:client_flutter_door/http/door.dart';

import 'package:client_flutter_door/http/mongo.dart';

import 'package:client_flutter_door/http/netframework.dart';
import 'package:client_flutter_door/utils/info.dart';
import 'package:client_flutter_door/utils/log.dart';
import 'package:client_flutter_door/vars.dart';
import 'package:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;

class DoorModel extends ChangeNotifier {
  IO.Socket socket = IO.io('ws://${Vars.server}');
  List<Cabinet> _boxs = [];
  List<String> _logs = [];
  List<Cabinet> get boxs => _boxs;
  List<String> get logs => _logs;

  Map<String, String> _userczhs = {};
  Map<String, String> get userczhs => _userczhs;
  getUserczhs() async {
    _userczhs = await Mongo.getUserczhs(
        DateFormat('yyyy-MM-dd').format(DateTime.now()));
    notifyListeners();
  }

  getLogs() async {
    _logs = await Log.getLogs();
  }

  getBoxs() async {
    try {
      final result = await Box.getBoxs();
      if (result.isNotEmpty) {
        _boxs = result;
        notifyListeners();
        debugPrint('_boxs.length******${_boxs.length}');
      } else {
        debugPrint('没有加载的锁数据信息');
        Info.snackbarWithoutContext('加载柜门锁信息失败');
        throw '加载柜门锁信息失败';
      }
    } catch (e) {
      Info.snackbarWithoutContext('加载柜门锁信息异常');
      debugPrint('加载柜门锁信息异常$e');
    }
  }

  Cabinet? getBox(int id) {
    if (_boxs.isNotEmpty) {
      Cabinet? box = _boxs.firstWhereOrNull((box) {
        return box.BlId == id;
      });
      return box;
    }
    return null;
  }

  setBoxOccupied(id, occupied) {
    debugPrint('_boxs.length:${_boxs.length}*****');
    Cabinet? box = _boxs.firstWhereOrNull((box) {
      if (box.id == id) {
        return true;
      }
      return false;
    });
    if (box != null) {
      box.occupied = occupied;
      notifyListeners();
    } else {
      Info.snackbarWithoutContext('没有匹配到柜门编号为$id');
    }
    // _boxs[id - 1].occupied = occupied;
    // notifyListeners();
  }

  String getHelperText() {
    int countCzh = 0;
    for (int i = 0; i < _boxs.length; i++) {
      if (_boxs[i].czh != '') {
        countCzh++;
      }
    }
    return '空柜子${_boxs.length - countCzh},占用柜子$countCzh';
  }

  DoorModel() {
    print('DoorModel结构执行');
    Timer.periodic(const Duration(seconds: 3), (timer) async {
      await Netframework.getAlcohol(_boxs);
    });
    //打开登录过期的没打开的柜门

    getBoxs();
    getLogs();
    getUserczhs();
  }
}
